package com.ruoyi.system.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * 身份证号码校验算法
 */
public class IdCardUtil {
    private static int[] weight = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 十七位数字本体码权重
    private static char[] validate = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' }; // mod11,对应校验码字符值
    // 得到校验码
    /**
     * @param IdNumber17 身份证前十七位
     * @return
     */
    private static char getCheckoutCode(String IdNumber17) {
        int sum = 0; // wi*Ai和
        int mod = 0; // 进行模11运算
        try {
            for (int i = 0; i < 17; i++) {
                sum += Integer.parseInt(String.valueOf(IdNumber17.charAt(i)))
                        * weight[i];
            }
        } catch (Exception e) {
            return 'a';
        }
        mod = sum % 11;// 进行模11运算
        return validate[mod];// 返回校验码
    }

    public static Boolean checkNumber(String idCard) throws CustomException {
        idCard = idCard.toUpperCase();
        if(StringUtils.isBlank(idCard)){
            return false;
        }
        if(idCard.length() != 18){
            return false;
        }
        String id17 = idCard.substring(0,17);
        char id1 = idCard.charAt(17);
        if(getCheckoutCode(id17) == id1) {
            return true;
        }else{
            return false;
        }
    }

    public static Boolean checkNumber2(String idCard,String msg) throws CustomException {
        if(StringUtils.isBlank(idCard)){
            throw new CustomException(msg+"不能为空");
        }
        if(idCard.length() != 18){
            throw new CustomException(msg+"长度不合法请重新输入!");
        }
        String id17 = idCard.substring(0,17);
        char id1 = idCard.charAt(17);
        if(getCheckoutCode(id17) == id1) {
            return true;
        }else{
            throw new CustomException(msg+"无效!");
        }
    }
}
